package cn.percent.parse;

import cn.percent.config.Configuration;
import cn.percent.io.Resources;
import cn.percent.utils.DBConnectionManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import org.dom4j.io.SAXReader;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }
    /**
     * 该方法就是使用dom4j对配置问价进行解析,封装Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        Properties properties = new Properties();
        List<Element> environment = rootElement.selectNodes("//environment");

        if (environment.size() == 1){
            String environmentId = environment.get(0).attributeValue("id");
            configuration.setEnvironmentId(environmentId);
            properties.setProperty("environmentId",environmentId);
        }

        List<Element> list = rootElement.selectNodes("//property");

        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        System.out.println(properties);
        /*
        * 数据库连接池，之后改成自己的代码
        * */
        DBConnectionManager instance = DBConnectionManager.getInstance(properties);
        configuration.setDataSource(instance);
//        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
//        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
//        comboPooledDataSource.setUser(properties.getProperty("username"));
//        comboPooledDataSource.setPassword(properties.getProperty("password"));
//        configuration.setDataSource(comboPooledDataSource);

        List<Element> mapperList = rootElement.selectNodes("//mapper");
        System.out.println(mapperList);
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            System.out.println(mapperPath);
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }
}
